/*----------------------------------------------------------------
// Copyright (C) 2011  博览财经资讯服务有限公司
// 版权所有
// 文件名：WebHelper
// 文件功能描述：用于asp.net的Helper类
// 
// 创建标识:王家新
// 
// 修改标识：
// 修改描述：
//         
// 修改标识：
// 修改描述：
//----------------------------------------------------------------*/

using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.IO;
using System.Net;
using System.Drawing;

namespace Aij1.Utils
{
    /// <summary>
    /// 用于asp.net的Helper类
    /// </summary>
    public class WebHelper
    {
        /// <summary>
        /// 获取Cookie
        /// </summary>
        /// <param name="cookieName"></param>
        /// <returns></returns>
        public static string GetCookie(String cookieName)
        {
            if (HttpContext.Current.Request.Cookies[cookieName] != null)
            {
                return HttpContext.Current.Request.Cookies[cookieName].Value;
            }
            return string.Empty;
        }

        /// <summary>
        /// 移除Cookie
        /// </summary>
        /// <param name="cookieName"></param>
        public static void RemoveCookie(String cookieName)
        {
            HttpCookie myCookie = new HttpCookie(cookieName);
            myCookie.Expires = DateTime.Now.AddDays(-1);
            HttpContext.Current.Response.Cookies.Add(myCookie);
        }

        /// <summary>
        /// 保存Cookie
        /// </summary>
        /// <param name="cookieName"></param>
        /// <param name="value"></param>
        public static void SetCookie(string cookieName, string value)
        {
            HttpCookie cookie = new HttpCookie(cookieName, value);
            HttpContext.Current.Response.Cookies.Add(cookie);
        }

        /// <summary>
        /// 保存Cookie
        /// </summary>
        /// <param name="cookieName"></param>
        /// <param name="value"></param>
        /// <param name="expireDays"></param>
        public static void SetCookie(string cookieName, string value, int expireDays)
        {
            HttpContext.Current.Response.Cookies[cookieName].Value = value;
            HttpContext.Current.Response.Cookies[cookieName].Expires = DateTime.Now.AddDays(expireDays);
        }

        /// <summary>
        /// 批量保存Cookie
        /// </summary>
        /// <param name="cookieName"></param>
        /// <param name="values"></param>
        /// <param name="CookiesKeyName"></param>
        public static void SetCookies(string cookieName, string[] values, string CookiesKeyName)
        {
            for (int i = 0; i < values.Length; i++)
            {
                HttpContext.Current.Response.Cookies[cookieName].Values.Add(CookiesKeyName.Split(new char[] { ',' })[i], values[i]);
            }
        }

        /// <summary>
        /// 批量获取Cookie
        /// </summary>
        /// <param name="cookieName"></param>
        /// <returns></returns>
        public static string[] GetCookies(String cookieName)
        {

            //if (HttpContext.Current.Request.Cookies.AllKeys.Contains(cookieName))
            //{
            //    List<String> Cookies = new List<string>();
            //    for (int i = 0; i < ontext.Current.Request.Cookies[cookieName].Values.Count; i++)
            //    {
            //        Cookies.Add(HttpContext.Current.Request.Cookies[cookieName].Values.Get(i));
            //    }
            //    return Cookies.ToArray();
            //}
            //else
            //{
            return null;
            //}
        }

        /// <summary>
        /// 是否允话
        /// </summary>
        /// <param name="en"></param>
        public static void ChkEnabled(bool en)
        {
            if (!en)
            {
                //可能要将非法操作记入数据库
                throw new Exception("您违反了操作规程.试图修改已冻结数据.");
            }
        }

        /// <summary>
        /// 获取绝对地址
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static string TrueUrl(object s)
        {
            return s.ToString().Replace("~/", HttpContext.Current.Request.ApplicationPath + "/").Replace("//", "/");
        }

        /// <summary>
        /// 提供一个文件下载的动作
        /// </summary>
        /// <param name="filePath"></param>
        public static void DownLoadFile(string filePath)
        {
            HttpResponse rsp = HttpContext.Current.Response;

            if (filePath.StartsWith("~/"))
            {
                filePath = HttpContext.Current.Server.MapPath(filePath);
            }

            FileStream f = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);

            rsp.ClearHeaders();
            rsp.ContentType = "application/x-msdownload";
            rsp.AddHeader("Content-Disposition", "attachment;filename= " + Path.GetFileName(filePath));
            rsp.AddHeader("Content-Length", f.Length.ToString());

            byte[] buffer = new byte[65536]; //担心一次读入大文件占内存，所以一块一块的读入。
            while (true)
            {
                int b = f.Read(buffer, 0, buffer.Length);


                if (b == 0) break;
                rsp.BinaryWrite(buffer);
            }
            f.Close();
            rsp.Flush();
            rsp.Close();
        }

        /// <summary>
        /// 请求指定url,并返回结果
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string GetWebResponse(string url)
        {
            try
            {
                HttpWebRequest smsReq = (HttpWebRequest)WebRequest.Create(url);
                WebResponse response = smsReq.GetResponse();
                Stream receiveStream = response.GetResponseStream();

                // Pipes the stream to a higher level stream reader with the required encoding format. 
                StreamReader readStream = new StreamReader(receiveStream);

                string result = readStream.ReadToEnd();
                response.Close();
                readStream.Close();
                return result;
            }
            catch
            {
                return String.Empty;
            }
        }

        /// <summary>
        /// 用Post方式请求指定url,并返回结果
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postData"></param>
        /// <returns></returns>
        public static string GetWebResponse(string url, string postData)
        {
            HttpWebRequest smsReq = (HttpWebRequest)WebRequest.Create(url);
            //将postData一起发送
            //...

            //postData = GetEncodeString(postData);
            smsReq.Method = "POST";
            //Encoding encoding = new Encoding();
            byte[] byte1 = Encoding.Default.GetBytes(postData);

            smsReq.ContentType = "application/x-www-form-urlencoded";
            smsReq.ContentLength = byte1.Length;

            Stream InputStream = smsReq.GetRequestStream();
            InputStream.Write(byte1, 0, byte1.Length);
            InputStream.Close();

            WebResponse response = smsReq.GetResponse();
            Stream receiveStream = response.GetResponseStream();

            // Pipes the stream to a higher level stream reader with the required encoding format. 
            StreamReader readStream = new StreamReader(receiveStream, System.Text.Encoding.Default);

            string result = readStream.ReadToEnd();
            response.Close();
            readStream.Close();
            return result;
        }

        /// <summary>
        /// 获取URL编码以后的字符串
        /// </summary>
        /// <param name="bs"></param>
        /// <returns></returns>
        public static String GetEncodeString(byte[] bs)
        {
            string encoded = "";

            if (bs == null) return null;

            if (bs.Length > 100)
            {
                StringBuilder sb = new StringBuilder(bs.Length * 5);
                foreach (byte b in bs)
                {
                    if (b < 128)
                    {
                        sb.Append(b);
                    }
                    else
                    {
                        sb.Append(String.Format("%{0:x}", b));
                    }
                }
                return sb.ToString();
            }
            else
            {
                foreach (byte b in bs)
                {
                    if (b < 128)
                    {
                        encoded += (char)b;
                    }
                    else
                    {
                        encoded += String.Format("%{0:x}", b);
                    }
                }
            }
            return encoded;
        }

        /// <summary>
        /// 获取URL编码以后的字符串
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static String GetEncodeString(string s)
        {
            byte[] bs = Encoding.Default.GetBytes(s);
            return GetEncodeString(bs);
        }

        /// <summary>
        /// 从网络URL获取流
        /// </summary>
        /// <param name="url">URL地址</param>
        /// <returns>Stream</returns>
        public static Stream GetStreamFromUrl(string url)
        {
            if (String.IsNullOrEmpty(url)) return null;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            WebResponse response = request.GetResponse();
            Stream stream = response.GetResponseStream();
            return stream;
        }

        /// <summary>
        /// 从网络URL获取图片
        /// </summary>
        /// <param name="url">URL地址</param>
        /// <returns>Stream</returns>
        public static Image GetImageFromUrl(string url)
        {
            if (String.IsNullOrEmpty(url)) return null;
            try
            {
                return Image.FromStream(GetStreamFromUrl(url));
            }
            catch (ArgumentException)
            {
                return null;
            }
            catch (WebException)
            {
                return null;
            }
        }

        /// <summary>
        /// 生成缩略图片
        /// </summary>
        /// <param name="filePath">源图片的完整路径</param>
        /// <param name="_width">缩略图的宽</param>
        /// <param name="_height">高</param>
        /// <returns></returns>
        public static Image CreateSnapShot(Image sourceImage, int _width, int _height)
        {
            //原图宽度和高度    
            int width = sourceImage.Width;
            int height = sourceImage.Height;
            int smallWidth;
            int smallHeight;

            //获取第一张绘制图的大小,(比较 原图的宽/缩略图的宽  和 原图的高/缩略图的高)    
            if (((decimal)width) / height <= ((decimal)_width) / _height)
            {
                smallWidth = _width;
                smallHeight = _width * height / width;
            }
            else
            {
                smallWidth = _height * width / height;
                smallHeight = _height;
            }

            //新建一个图板,以最小等比例压缩大小绘制原图    
            System.Drawing.Image bitmap = new System.Drawing.Bitmap(smallWidth, smallHeight);

            using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap))
            {

                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
                g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                g.Clear(Color.Black);
                g.DrawImage(
                sourceImage,
                new System.Drawing.Rectangle(0, 0, smallWidth, smallHeight),
                new System.Drawing.Rectangle(0, 0, width, height),
                System.Drawing.GraphicsUnit.Pixel
                );
                g.Dispose();
            }
            return bitmap;
        }
    }
}
                                                                                                                                                                                        